package com.example.demo.test;

import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.ContentHandler;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

    // 本地文件路径（注意 Windows 路径中的反斜杠要转义，或使用双反斜杠或正斜杠）
    private static final String FILE_PATH = "C:\\file\\";

    @GetMapping("/download/{path}")
    public void downloadFile(HttpServletResponse response, @PathVariable String path) throws IOException {
        File file = new File(FILE_PATH+ path);

        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("File not found: " + FILE_PATH);
            return;
        }
        String fileMD5 = MD5Util.getFileMD5(file);
        System.out.println(fileMD5);


        System.out.println(""+ file.length());

        // 设置响应头：告诉浏览器这是文件下载
        response.setContentType("application/octet-stream"); // 通用二进制流
        response.setContentLengthLong(file.length());

        // 中文文件名编码，避免乱码
        String encodedFileName = URLEncoder.encode(path, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        // 写入文件流到响应
        try (InputStream in = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            throw e; // 可以记录日志
        }
    }




    @PostMapping("/create")
    public String createMaterial(@RequestBody MultipartFile file) {
        try {
            long duration = 0;
            duration = getDuration(file.getInputStream());
        System.out.println(duration);
        file.getInputStream().close();
        return "duration: " + duration;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 使用 Apache Tika 获取音视频文件时长（单位：秒，四舍五入）
     *
     * @param inputStream 文件输入流
     * @return 时长（秒），失败返回 0
     */
    public long getDuration(InputStream inputStream) {
        try {
            AutoDetectParser parser = new AutoDetectParser();
            Metadata metadata = new Metadata();
            ContentHandler handler = new BodyContentHandler(); // 不需要内容，只取 metadata

            // 解析文件
            parser.parse(inputStream, handler, metadata);

            // 获取时长（单位：秒，字符串形式）
            String durationStr = metadata.get("xmpDM:duration");
            if (durationStr != null && !durationStr.trim().isEmpty()) {
                return Math.round(Float.parseFloat(durationStr));
            }

            // 备用字段（某些格式用 "duration" 或 "length"）
            durationStr = metadata.get("duration"); // 有些格式是毫秒
            if (durationStr != null && !durationStr.trim().isEmpty()) {
                float duration = Float.parseFloat(durationStr);
                // 如果是毫秒（如 MP4），转为秒
                if (duration > 10000) { // > 10秒，大概率是毫秒
                    return Math.round(duration / 1000f);
                }
                return Math.round(duration);
            }

        } catch (Exception e) {
            // 解析失败不中断业务，记录日志或监控
            e.printStackTrace();
        }
        return 0; // 默认 0
    }

}